package cn.hy.face.utils;

import cn.hy.face.common.vo.PageInfo;
import org.springframework.util.CollectionUtils;
import java.util.List;

/**
 * @program: pms-interface
 * @author: qingxiangen
 * @create: 2019-08-19 09:12
 * @description: 分页处理
 **/
public class PageUtils {

    /**
     * 分页处理
     * @param list
     * @param pageNumBox
     * @param pageSizeBox
     * @return
     */
    public static<T> PageInfo<T> buildPageInfo(List<T> list, Integer pageNumBox, Integer pageSizeBox){
        PageInfo<T> pageInfo = new PageInfo<>();
        if(CollectionUtils.isEmpty(list)){
            pageInfo.setList(list);
            return pageInfo;
        }
        //无需分页处理
        if(pageNumBox == null || pageSizeBox == null){
            pageInfo.setList(list);
            return pageInfo;
        }
        int pageNum = pageNumBox.intValue();
        int pageSize = pageSizeBox.intValue();
        int size = list.size();
        //从第几条数据开始
        int firstIndex = (pageNum - 1) * pageSize;
        if(firstIndex > size){
            firstIndex = size;
        }
        //到第几条数据结束
        int lastIndex = pageNum * pageSize;
        if(lastIndex > size){
            lastIndex = size;
        }
        int pages = (size + pageSize -1) / pageSize;
        boolean isFirstPage = pageNum == 1;
        boolean isLastPage = false;
        if(pages > 1){
            isLastPage = pageNum == pages;
        }
        List<T> pageList = list.subList(firstIndex, lastIndex);
        pageInfo.setList(pageList);
        pageInfo.setIsFirstPage(isFirstPage);
        pageInfo.setIsLastPage(isLastPage);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPages(pages);
        pageInfo.setTotal(list.size());
        return pageInfo;
    }
}
